class Solution {
public:
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int uniquePathsIII(vector<vector<int>>& grid)
    {
        int n = grid.size(), m = grid[0].size();
        int ans = 0;
        vector<vector<bool>> vis(n, vector<bool>(m, false));
        function<void(int, int)> dfs = [&](int i, int j) {
            if (grid[i][j] == 2)
            {
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < m; j++)
                        if (grid[i][j] == 0 && vis[i][j] == false)
                            return;
                ans++;
                return;
            }
            for (int a = 0; a < 4; a++)
            {
                int x = dx[a] + i, y = dy[a] + j;
                if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && grid[x][y] != -1 && grid[x][y] != 1)
                {
                    vis[x][y] = true;
                    dfs(x, y);
                    vis[x][y] = false;
                }
            }
            };

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (grid[i][j] == 1)
                {
                    dfs(i, j);
                    return ans;
                }
            }
        }
        return ans;
    }
};